package com.mf.dispatcher;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.mf.controller.AdminController;
import com.mf.controller.UserController;
import com.mf.entity.Msg;


@WebServlet("/user/*")
public class UserDispather extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String traget;
	
    public UserDispather() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url= request.getRequestURI();
		String myUrl = url.substring(url.lastIndexOf("/")+1);
		response.setContentType("application/json; charset=utf-8"); 
		String username;
		String password;
		AdminController adminController=new AdminController();
		PrintWriter out=response.getWriter();
		String jsonString;
		switch(myUrl){
			case "login":
				username=request.getParameter("username");
				password=request.getParameter("password");
				Msg msg=adminController.adminLogin(username, password);
				if(msg.getCode()==100){
					HttpSession session = request.getSession(false);
					session.setAttribute("user", username);
				}
				 jsonString=JSON.toJSONString(msg);
				traget = jsonString;
				out=response.getWriter();
				out.println(traget);
				break;
			case "logout":
				HttpSession session = request.getSession(false);
				session.removeAttribute("user");
				 jsonString=JSON.toJSONString(Msg.success());
				traget = jsonString;
				out=response.getWriter();
				out.println(traget);
				break;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
